import {loginInterface, getUserDetail, quit} from "@/network/login/login";
import {checkCode} from "@/store/exception";
import {getCookie, removeCookie, setCookie} from "@/until/cookie";

interface stateInterface {
    isShowLoginDialog: boolean;
    userDetail: any | undefined;
    isLogin: boolean;
}

export default {
    namespaced: true,
    state: {
        isShowLoginDialog: false,
        userDetail: undefined,
        isLogin: false,
    },
    mutations: {
        CHANGE_IS_SHOW_LOGIN_DIALOG(state: stateInterface, value: boolean) {
            state.isShowLoginDialog = value;
        },
        CHANGE_IS_LOGIN(state: stateInterface, value: boolean) {
            state.isLogin = value;
        },
        SAVE_USER_DETAIL(state: stateInterface, value: any) {
            state.userDetail = value;
            state.isLogin = true;
        },
        QUIT(state: stateInterface) {
            removeCookie();
            state.isLogin = false;
            state.userDetail = undefined;
            window.localStorage.removeItem("userId");
        },
    },
    actions: {
        //用户登陆接口
        async userLogin(context: any, value: { username: string; password: string }) {
            const {data: loginData} = await loginInterface(value.username, value.password);
            //保存cookie
            setCookie(loginData.cookie);
            window.localStorage.setItem("userId", loginData.account.id);
            const {data: userDetail} = await getUserDetail(loginData.account.id);
            context.commit("SAVE_USER_DETAIL", userDetail);
        },
        //用户登陆过且没有选择退出，下次进入时直接启用存储的用户id
        async userHadLogin(context: any, value: number) {
            const {data: userDetail} = await getUserDetail(value);
            context.commit("SAVE_USER_DETAIL", userDetail);
        },
        async quit(context: any) {
            await quit();
            context.commit("QUIT");
        },
    },
    getters: {},
};
